﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Yipusoft.TownshipEnterprise.Model;
using Yipusoft.TownshipEnterprise.BLL;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using Yipusoft.MapInfo.Model;
using Yipusoft.Account.Model;

public partial class TownshipEnterprise_Institutions : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlType.SelectedIndex = 0;
            ddlType_SelectedIndexChanged(sender, e);

            if (String.IsNullOrEmpty(Request["ID"]))
                BindDepartment("203001", "203002", "203003");
            else
                BindDepartment("203001", "203004", "203005");

            ddlDepartment.SelectedIndex = 0;
            DepartmentList_SelectedIndexChanged(sender,e);
        }
    }

    private void BindDepartment(string permissionAdmin, string permissionLevel, string permissionUnit)
    {
        UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        Yipusoft.Account.Model.DepartmentInfo department = Yipusoft.Account.BLL.Department.GetDepartment(userInfo.DepartmentID);
        string departmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        //ddlDepartment.DataSource = Department.GetList(" DepartmentId like '%000' or departmentId ='1312100' or departmentId='1313100'");
        //ddlDepartment.DataBind();


        //UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        Yipusoft.Account.Model.DepartmentInfo departmentIDs = Yipusoft.Account.BLL.Department.GetDepartment(userInfo.DepartmentID);
        if (userInfo.DepartmentID.Substring(0, 4) == "1300")
        {
            ddlDepartment.DataSource = Yipusoft.Account.BLL.Department.GetList(" (SUBSTRING(DepartmentID, 5, 3) = '000') and DepartmentID<>'1300000' ");
            ddlDepartment.DataBind();
            DepartmentListBind();
        }
        else
        {
            ddlDepartment.DataSource = Yipusoft.Account.BLL.Department.GetList(" DepartmentID= '" + departmentIDs.DepartmentID.Substring(0, 4) + "000' ");
            ddlDepartment.DataBind();
            DepartmentListBind();
        }



        if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionAdmin))
        {
            BingDDLBasicInfo();
        }
        else if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionLevel))
        {
            if (departmentID.Substring(0, 5) == "13121")
            {
                ddlDepartment.SelectedValue = departmentID;
            }
            else
                if (departmentID == "1313100")
                {
                    ddlDepartment.SelectedValue = departmentID;
                }
                else
                {
                    ddlDepartment.SelectedValue = departmentID.Substring(0, 4) + "000";
                }
            ddlDepartment.Enabled = false;
            BingDDLBasicInfo();
        }
        else
            if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionUnit))
            {
                ddlDepartment.SelectedValue = departmentID.Substring(0, 4) + "000";
                ddlDepartment.Enabled = false;
                BingDDLBasicInfo();
                UnitList.SelectedValue = departmentID;
                UnitList.Enabled = false;
            }

    }

    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (ddlType.SelectedValue)
        {
            case "协议文件":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("当地人民政府与企事业专职消防队签署的整合改革工作相关协议");
                //ddlName.Items.Add("有无责任区域划分协议");
                //ddlName.Items.Add("有无日常业务经费补贴协议");
                lblInfo.Text = "当地人民政府与企事业专职消防队签署的整合改革工作相关协议";
                break;
            case "责任区域":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("本单位附近责任区域");
                //ddlName.Items.Add("有无责任区域划分协议");
                //ddlName.Items.Add("有无日常业务经费补贴协议");
                lblInfo.Text = "本单位附近责任区域";
                break;
            case "经济补偿":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("参加外单位扑救火灾所耗燃料器材装备等是否由受益区所在区政府给与补偿");
                lblInfo.Text = "参加外单位扑救火灾所耗燃料器材装备等是否由受益区所在区政府给与补偿";
                break;
            case "经费保障":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("经费应纳入本单位年度预算予以保障，人员工资、福利、政治待遇等按照本单位有关规定执行");
                lblInfo.Text = "经费应纳入本单位年度预算予以保障，人员工资、福利、政治待遇等按照本单位有关规定执行";
                break;
            case "执勤制度":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("参照《公安消防部队执勤战斗条令》有关要求，建立健全交接班、战备教育、等级战备、战备检查等制度");
                lblInfo.Text = "参照《公安消防部队执勤战斗条令》有关要求，建立健全交接班、战备教育、等级战备、战备检查等制度";
                break;
            case "训练制度":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("参照《公安消防部队灭火救援业务训练与考核大纲》有关要求，建立健全计划、检查、考核、奖惩等训练制度，定期开展灭火救援演练");
                lblInfo.Text = "参照《公安消防部队灭火救援业务训练与考核大纲》有关要求，建立健全计划、检查、考核、奖惩等训练制度，定期开展灭火救援演练";
                break;
            case "档案记录":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("各种软件记录、管理规定参照公安消防部队执行");
                lblInfo.Text = "各种软件记录、管理规定参照公安消防部队执行";
                break;
            case "业务指导":
                //ddlName.Items.Clear();
                //ddlName.Items.Add("各级公安消防机构应加强对企事业专职消防队执勤备战、业务训练工作进行考核、检查、指导，并组织企事业专职消防队开展业务培训");
                lblInfo.Text = "各级公安消防机构应加强对企事业专职消防队执勤备战、业务训练工作进行考核、检查、指导，并组织企事业专职消防队开展业务培训";
                break;
        }
    }
  
    //保存信息，上传图片
    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        Guid tbid = Guid.NewGuid();
        try
        {
            //tbid = (Guid)ViewState["TownBasicID"];

        }
        catch (Exception)
        {
            Response.Write("<script language=javascript>alert('请先保存单位信息！')</script>");
            return;
        }

        //保存图片
        HttpFileCollection files = HttpContext.Current.Request.Files;
        //string ssf = files.Get("ctl00$ContentPlaceHolder1$TabContainer1$TabPanel2$fuPhoto").FileName;   //

        HttpPostedFile file = files.Get("ctl00$ContentPlaceHolder1$fuPhoto");
        string path = string.Empty;
        string picName = DateTime.Now.ToString("yyyyMMddHHmmssff");
        bool img = SaveImg(picName, "6", file, out path);

        if (img)
        {

            //保存到数据库

            try
            {
                TownPicsInfo pic = new TownPicsInfo();
                pic.id = Guid.NewGuid();
                pic.TownBasicInfoID = tbid;
                pic.TownPicstypeID = ddlType.SelectedValue;
                pic.TownItemsID = "6";
                pic.PicPath = path;
                pic.PicDescript = txtPhotoDetails.Text;

                bool b = TownPics.Insert(pic);

                if (b)
                {
                    Response.Write("<script language=javascript>alert('保存成功！')</script>");
                    BindDateList(tbid.ToString());
                    return;
                }
                else
                {
                    //从硬盘删除图片文件
                    string allPath = Request.MapPath("") + path;
                    try
                    {
                        File.Delete(allPath);

                    }
                    catch
                    { }
                }
            }
            catch
            {
                string allPath = Request.MapPath("") + path;
                try
                {
                    File.Delete(allPath);
                }
                catch
                { }
            }
            Response.Write("<script language=javascript>alert('保存失败，请重新上传！')</script>");
        }
        else
        {
            Response.Write("<script language=javascript>alert('图片格式不正确，请上传 *.bmp,*.jpg,*.jpeg 格式图片')</script>");
        }
    }
    
    //删除图片
    protected void btnDelete_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandArgument == null)
            return;
        Guid id = new Guid(e.CommandArgument.ToString());

        string path = TownPics.GetTownPics(id).PicPath;
        if (TownPics.Delete(id))
        {
            //删除文件
            string allPath = Request.MapPath("") + "\\" + @path;
            try
            {
                File.Delete(allPath);
            }
            catch (Exception ex) { }

            Response.Write("<script language=javascript>alert('删除成功。')</script>");
            //重新显示图片
            BindDateList(id.ToString());
        }
        else
        {
            Response.Write("<script language=javascript>alert('删除失败。')</script>");
        }
    }
    protected void btnEdit_Command(object sender, CommandEventArgs e)
    {

    }


    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="name1">图片名称，不包含扩展名</param>
    /// <param name="typepath">图片分类目录TownItems表id</param>
    /// <param name="localPath">返回站点相对路径和文件名</param>
    /// <param name="postedFile">单独文件上传流</param>
    /// <returns></returns>
    private bool SaveImg(string name1, string typepath, HttpPostedFile postedFile, out string localPath)
    {
        //HttpFileCollection files = HttpContext.Current.Request.Files;
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        bool fileOk = false;



        //HttpPostedFile postedFile = files[0];

        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        if (fileName != "")
        {
            fileExtension = System.IO.Path.GetExtension(fileName);
            String[] allowedExtensions = { ".jpg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension.ToLower() == allowedExtensions[i])
                {
                    fileOk = true;
                    break;
                }
            }
        }
        if (fileOk)
        {

            //Bitmap bm = new Bitmap(path);
            //本地image文件夹路径
            string sPath = System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\");
            //文件扩展名
            fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
            //随机文件名
            Random rnd = new Random();
            // string newName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + rnd.Next(1000).ToString();
            string newName = name1;
            localPath = "UpLoadImages\\" + typepath + "\\" + newName + fileExtension;
            // postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension);

            // Bitmap bmp = new Bitmap(postedFile.InputStream);



            double width = 1024;
            double height = 768;
            //从文件取得图片对象
            System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
            System.Double NewWidth, NewHeight;

            if (image.Width > image.Height)
            {
                NewWidth = width;
                NewHeight = image.Height * (NewWidth / image.Width);
            }
            else
            {
                NewHeight = height;
                NewWidth = (NewHeight / image.Height) * image.Width;
            }

            if (NewWidth > width)
            {
                NewWidth = width;
            }
            if (NewHeight > height)
            {
                NewHeight = height;
            }

            //取得图片大小
            System.Drawing.Size size = new Size((int)NewWidth, (int)NewHeight);
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空一下画布
            g.Clear(System.Drawing.Color.White);
            //在指定位置画图
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            System.Drawing.GraphicsUnit.Pixel);

            //保存高清晰度的缩略图
            bitmap.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\") + newName + fileExtension, ImageFormat.Jpeg);

            // bmp.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension, ImageFormat.Jpeg);


            return true;

        }
        else
        {
            //提示
            localPath = "";
            return false;
        }

    }


    /// <summary>
    /// 显示库室图片
    /// </summary>
    /// <param name="PerformanceID">单位id</param>
    void BindDateList(string PerformanceID)
    {
        string strWhere = "TownBasicInfoID='" + PerformanceID + "' and TownItemsID='6'";
        List<TownPicsInfo> listPics = TownPics.GetList("TownBasicInfoID", "desc", strWhere, 20, 0);

        //foreach (TownPicsInfo pic in listPics)
        //{
        //    pic.TownPicstypeID = TownPicsType.GetTownPicsType(pic.TownPicstypeID).PicType;
        //}


        DltList.DataSource = listPics;
        DltList.DataBind();
    }
    protected void DepartmentList_SelectedIndexChanged(object sender, EventArgs e)
    {
        DepartmentListBind();
    }

    /// <summary>
    /// 绑定县
    /// </summary>
    void DepartmentListBind()
    {
        UnitList.Items.Clear();
        string strWhere = "DepartmentID like '" + ddlDepartment.SelectedValue.Substring(0, 4) + "2%' and   SUBSTRING(DepartmentID, 5, 1)<>'0' and shortname like'%大队'";
        List<Yipusoft.Account.Model.DepartmentInfo> list = Yipusoft.Account.BLL.Department.GetList(strWhere);
        foreach (Yipusoft.Account.Model.DepartmentInfo dpt in list)
        {
            dpt.ShortName = dpt.ShortName.Replace("大队", "");
            dpt.ShortName = dpt.ShortName.Replace("消防", "");
        }
        UnitList.DataSource = list;
        UnitList.DataBind();
        BingDDLBasicInfo();
    }

    protected void UnitList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BingDDLBasicInfo();
    }

    /// <summary>
    /// 绑定消防队
    /// </summary>
    void BingDDLBasicInfo()
    {
        ddlTownBasic.Items.Clear();
        string strWhere = " DepartmentID='" + UnitList.SelectedValue.ToString() + "'";
        List<TownBasicInfo> list = TownBasic.GetList(strWhere);
        if (list.Count == 0)
        {
            btnUpLoad.Enabled = false;
            lblInfo.Text = "错误：没有可添加信息的消防队，请先添加此地区消防队。";
            ddlTownBasic.Items.Add("此地区没有消防队");

            string colorStr = System.Drawing.ColorTranslator.ToHtml(Color.Red);
            ddlTownBasic.Items[0].Attributes.Add("style", "color:" + colorStr);

            return;
        }
        else
        {
            btnUpLoad.Enabled = true;
            lblInfo.Text = "";
            ddlTownBasic.DataSource = list;
            ddlTownBasic.DataBind();
        }
    }
}
